using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OrderingSystem.Core.Entities;
using OrderingSystem.Infrastructure.Data;
using System.Text;
using System.Security.Claims;

namespace OrderingSystem.API.Controllers
{
    [ApiController]
    [Route("dingdanxinxi")]
    public class OrderInfoController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public OrderInfoController(ApplicationDbContext context)
        {
            _context = context;
            // 在构造函数中打印表结构信息，帮助调试
            PrintTableStructure();
        }

        private void PrintTableStructure()
        {
            try
            {
                var entityType = _context.Model.FindEntityType(typeof(Order));
                if (entityType != null)
                {
                    var tableName = entityType.GetTableName();
                    var properties = entityType.GetProperties();
                    
                    var sb = new StringBuilder();
                    sb.AppendLine($"表名: {tableName}");
                    sb.AppendLine("列名:");
                    
                    foreach (var property in properties)
                    {
                        sb.AppendLine($"  {property.Name} -> {property.GetColumnName()}");
                    }
                    
                    Console.WriteLine(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"打印表结构时出错: {ex.Message}");
            }
        }

        [HttpGet("page")]
        [AllowAnonymous]
        public async Task<IActionResult> GetOrdersPage(
            [FromQuery] int page = 1, 
            [FromQuery] int limit = 10,
            [FromQuery] string sort = "addtime",
            [FromQuery] string order = "desc",
            [FromQuery] string status = null)
        {
            try
            {
                // 直接使用简单查询，不使用别名
                var query = _context.Orders.AsQueryable();

                // 筛选状态
                if (!string.IsNullOrEmpty(status))
                {
                    query = query.Where(o => o.sfsh == status);
                }

                // 排序
                if (sort == "addtime")
                {
                    query = order == "desc" 
                        ? query.OrderByDescending(o => o.addtime)
                        : query.OrderBy(o => o.addtime);
                }
                else if (sort == "id")
                {
                    query = order == "desc" 
                        ? query.OrderByDescending(o => o.id)
                        : query.OrderBy(o => o.id);
                }

                // 先获取总数
                var totalCount = await query.CountAsync();

                // 然后获取分页数据
                var orders = await query
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .Select(o => new
                    {
                        id = o.id,
                        addtime = o.addtime,
                        dingdanbianhao = o.dingdanbianhao,
                        caipinmingcheng = o.caipinmingcheng,
                        caipinfenlei = o.caipinfenlei,
                        tupian = o.tupian,
                        caipinjiage = o.caipinjiage,
                        shuliang = o.shuliang,
                        zongjine = o.zongjine,
                        xiadanshijian = o.xiadanshijian,
                        songcandizhi = o.songcandizhi,
                        yonghuming = o.yonghuming,
                        lianxidianhua = o.lianxidianhua,
                        sfsh = o.sfsh,
                        shhf = o.shhf,
                        ispay = o.ispay,
                        userid = o.userid
                    })
                    .ToListAsync();

                return Ok(new
                {
                    code = 0,
                    data = new
                    {
                        total = totalCount,
                        pageSize = limit,
                        totalPage = (int)Math.Ceiling((double)totalCount / limit),
                        currPage = page,
                        list = orders
                    }
                });
            }
            catch (Exception ex)
            {
                // 记录异常
                Console.WriteLine($"获取订单分页数据时发生错误: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                
                // 返回错误响应
                return StatusCode(500, new { code = 500, msg = "服务器内部错误", error = ex.Message });
            }
        }

        [HttpGet("list")]
        [AllowAnonymous]
        public async Task<IActionResult> GetOrders([FromQuery] string status = null)
        {
            try
            {
                var query = _context.Orders.AsQueryable();
                
                if (!string.IsNullOrEmpty(status))
                {
                    query = query.Where(o => o.sfsh == status);
                }
                
                var orders = await query
                    .OrderByDescending(o => o.addtime)
                    .Select(o => new
                    {
                        id = o.id,
                        addtime = o.addtime,
                        dingdanbianhao = o.dingdanbianhao,
                        caipinmingcheng = o.caipinmingcheng,
                        caipinfenlei = o.caipinfenlei,
                        tupian = o.tupian,
                        caipinjiage = o.caipinjiage,
                        shuliang = o.shuliang,
                        zongjine = o.zongjine,
                        xiadanshijian = o.xiadanshijian,
                        songcandizhi = o.songcandizhi,
                        yonghuming = o.yonghuming,
                        lianxidianhua = o.lianxidianhua,
                        sfsh = o.sfsh,
                        shhf = o.shhf,
                        ispay = o.ispay,
                        userid = o.userid
                    })
                    .ToListAsync();

                return Ok(new { code = 0, data = orders });
            }
            catch (Exception ex)
            {
                // 记录异常
                Console.WriteLine($"获取订单列表时发生错误: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                
                // 返回错误响应
                return StatusCode(500, new { code = 500, msg = "服务器内部错误", error = ex.Message });
            }
        }

        [HttpGet("detail/{id}")]
        [AllowAnonymous]
        public async Task<IActionResult> GetOrderDetail(long id)
        {
            try
            {
                var order = await _context.Orders
                    .Select(o => new
                    {
                        id = o.id,
                        addtime = o.addtime,
                        dingdanbianhao = o.dingdanbianhao,
                        caipinmingcheng = o.caipinmingcheng,
                        caipinfenlei = o.caipinfenlei,
                        tupian = o.tupian,
                        caipinjiage = o.caipinjiage,
                        shuliang = o.shuliang,
                        zongjine = o.zongjine,
                        xiadanshijian = o.xiadanshijian,
                        songcandizhi = o.songcandizhi,
                        yonghuming = o.yonghuming,
                        lianxidianhua = o.lianxidianhua,
                        sfsh = o.sfsh,
                        shhf = o.shhf,
                        ispay = o.ispay,
                        userid = o.userid
                    })
                    .FirstOrDefaultAsync(o => o.id == id);
                
                if (order == null)
                {
                    return NotFound(new { code = 404, msg = "订单不存在" });
                }

                return Ok(new { code = 0, data = order });
            }
            catch (Exception ex)
            {
                // 记录异常
                Console.WriteLine($"获取订单详情时发生错误: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                
                // 返回错误响应
                return StatusCode(500, new { code = 500, msg = "服务器内部错误", error = ex.Message });
            }
        }

        [HttpGet("info/{id}")]
        [AllowAnonymous]
        public async Task<IActionResult> GetOrderInfo(long id)
        {
            return await GetOrderDetail(id);
        }

        /// <summary>
        /// 添加订单
        /// </summary>
        [HttpPost("add")]
        [Authorize]
        public async Task<IActionResult> CreateOrder([FromBody] CreateOrderInfoModel model)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrEmpty(model.caipinmingcheng))
                {
                    return Ok(new { code = 1, msg = "菜品名称不能为空" });
                }
                if (string.IsNullOrEmpty(model.caipinfenlei))
                {
                    return Ok(new { code = 1, msg = "菜品分类不能为空" });
                }
                if (model.caipinjiage == null || model.caipinjiage <= 0)
                {
                    return Ok(new { code = 1, msg = "菜品价格必须大于0" });
                }
                if (model.shuliang <= 0)
                {
                    return Ok(new { code = 1, msg = "数量必须大于0" });
                }
                if (model.zongjine <= 0)
                {
                    return Ok(new { code = 1, msg = "总金额必须大于0" });
                }
                if (string.IsNullOrEmpty(model.songcandizhi))
                {
                    return Ok(new { code = 1, msg = "送餐地址不能为空" });
                }

                var userId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "0");
                var user = await _context.Users.FindAsync(userId);
                if (user == null)
                {
                    return Ok(new { code = 1, msg = "用户不存在" });
                }

                var order = new Order
                {
                    dingdanbianhao = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000, 9999).ToString(),
                    caipinmingcheng = model.caipinmingcheng,
                    caipinfenlei = model.caipinfenlei,
                    tupian = model.tupian,
                    caipinjiage = model.caipinjiage,
                    shuliang = model.shuliang,
                    zongjine = model.zongjine.ToString("0.00"),
                    xiadanshijian = DateTime.Now,
                    songcandizhi = model.songcandizhi,
                    yonghuming = user.yonghuming,
                    lianxidianhua = user.lianxidianhua,
                    userid = userId,
                    sfsh = "否",
                    ispay = "未支付",
                    addtime = DateTime.Now
                };

                _context.Orders.Add(order);
                await _context.SaveChangesAsync();

                return Ok(new { code = 0, msg = "下单成功", data = order });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"创建订单时发生错误: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                var innerException = ex.InnerException != null ? $"\nInner Exception: {ex.InnerException.Message}" : "";
                return Ok(new { code = 1, msg = $"下单失败: {ex.Message}{innerException}" });
            }
        }
    }

    public class CreateOrderInfoModel
    {
        public string caipinmingcheng { get; set; }
        public string caipinfenlei { get; set; }
        public string tupian { get; set; }
        public int? caipinjiage { get; set; }
        public int shuliang { get; set; }
        public decimal zongjine { get; set; }
        public string songcandizhi { get; set; }
    }
} 